import fileUtils from "@/utils/fileUtils.js";
// 表格相关方法
export function checkMobile(rule, value, cb) {
  const regMobile = /^^1[0-9]{10}$/;
  if (regMobile.test(value)) {
    return cb();
  }
  cb(new Error("请输入合法的手机号"));
}
export function checkIdcard(rule, value, cb) {
  if (this.documentTypeFlag) {
    const regCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (regCard.test(value)) {
      return cb();
    }
    cb(new Error("身份证输入不合法"));
  }
  return cb();
}
export function checkName(rule, value, cb) {
  const regName = /^[\u4E00-\u9FA5]{2,16}$/;
  if (regName.test(value)) {
    return cb();
  }
  cb(new Error("请输入2-16个汉字！"));
}

/**
 * element上传组件处理函数
 * @param {*} file
 * @returns
 */
export function beforeRead(file) {
  return new Promise(resolve => {
    fileUtils.getOrientation(file).then(orient => {
      let reader = new FileReader();
      let img = new Image();
      reader.onload = e => {
        img.src = e.target.result;
        img.onload = async function() {
          let width = 600,
            height = 600 * (img.height / img.width);
          const data = await fileUtils.rotateImage(img, width, height, orient);
          const newFile = await fileUtils.dataURLtoFile(data, file.name);
          resolve(newFile);
        };
      };
      reader.readAsDataURL(file);
    });
  });
}
export function readFile(file, encoding) {
  return new Promise(function(resolve, reject) {
    var reader = new FileReader();
    if (encoding && reader["readAs" + encoding]) reader["readAs" + encoding](file);
    else reader.readAsText(file, encoding);
    reader.onload = function(e) {
      resolve(e.target.result);
    };
    reader.onerror = reject;
  });
}

/**
 * 图片转为base64
 * @param {Blob} file
 * @returns {Promise<string>}
 */
export function getBase64(file) {
  return new Promise(function(resolve, reject) {
    let reader = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function() {
      imgResult = reader.result;
    };
    reader.onloadend = function() {
      resolve(imgResult);
    };
    reader.onerror = reject;
  });
}

/**
 * 加密身份证，电话
 * @param {String} str
 * @param {Number} [hNum] 前面显示的数量
 * @param {Number} [eNum] 后面显示的数量
 * @returns {String} 123***1231
 */
export function hideOfString(str, hNum = 3, eNum = 4) {
  if (!str) return;
  let s = str.slice(0, hNum) + "***" + str.slice(str.length - eNum);
  return s;
}
//名字脱敏
export function formatName(name) {
  var newStr;
  if (name.length === 2) {
    newStr = name.substr(0, 1) + "*";
  } else if (name.length > 2) {
    var char = "";
    for (var i = 0, len = name.length - 2; i < len; i++) {
      char += "*";
    }
    newStr = name.substr(0, 1) + char + name.substr(-1, 1);
  } else {
    newStr = name;
  }
  return newStr;
}
